package org.bikelab.se3.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TrigChunker {
	public static void chunk(String inputPath, String outputPath) throws IOException {
		int maxLine = 500000;
		int fileCounter = 0;
		int lineCounter = 0;
		
		File inputFile = new File(inputPath);
		
		BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile)));
		FileWriter writer = null;

		String line = null;
		String graphName = null;
		
		String patternStr = "_:(\\w+)";
		String replaceStr = "<http://blanknode.com/$1>";
		Pattern pattern = Pattern.compile(patternStr);

		while((line = reader.readLine()) != null) {
			line = line.trim();
			if(line.isEmpty()) {
			} if(graphName == null && line.endsWith("{")) {
				graphName = line;
			} else if(line.startsWith("}")) {
				graphName = null;
			} else if(graphName != null) {
				if(line.contains("_:")) {
					line.replaceAll("_:", "<http://blanknode.com/");
					Matcher matcher = pattern.matcher(line);
					line = matcher.replaceAll(replaceStr);
				}
//				System.out.println(line);
				if(lineCounter % maxLine == 0 && line.startsWith("<http")) {
					if(writer != null) {
						writer.write("}");
						writer.close();
					}
					String outputFile = outputPath + "/" + inputFile.getName().replace(".trig", "");
					outputFile +=  "_" + fileCounter + ".trig";
					writer = new FileWriter(outputFile);
					writer.write(graphName + "\n");
					fileCounter++;
				}
				
				writer.write(line + "\n");
				if(line.startsWith("<http")) {
					lineCounter++;
				}
			}
		}
		if(writer != null) {
			writer.write("}");
			writer.close();
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			chunk("trig2nq/input/" + "cell-map.trig", "trig2nq/tmp");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
